package com.magic.himalaya;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.Layout;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.magic.himalaya.adapters.SearchAdapter;
import com.magic.himalaya.interfaces.ISearchViewCallBack;
import com.magic.himalaya.presenters.AlbumDetailPresenter;
import com.magic.himalaya.presenters.SearchPresenter;
import com.magic.himalaya.utils.Constants;
import com.magic.himalaya.utils.DisplayUtils;
import com.magic.himalaya.utils.LogUtil;
import com.magic.himalaya.views.LoaderView;
import com.ximalaya.ting.android.opensdk.model.album.Album;
import com.ximalaya.ting.android.opensdk.model.word.HotWord;
import com.ximalaya.ting.android.opensdk.model.word.QueryResult;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.Inflater;

public class SearchActivity extends AppCompatActivity implements ISearchViewCallBack {
    private String TAG = "SearchActivity";

    private ImageView mBtn_back;
    private EditText mEd_search_content;
    private TextView mBtn_search_go;
    private SearchPresenter mSearchPresenter;
    private LoaderView mLoaded;
    private FrameLayout mFramelayout;
    private LinearLayout mHotwordFragment;
    private SearchAdapter mSearchAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);


        mSearchPresenter = SearchPresenter.getInstance();//获得搜索逻辑层实例
        mSearchPresenter.registerViewCallBack(this);

        init();
        initView();
        initEvent();
        mSearchPresenter.getHotWord();

    }

    private void init() {
        mBtn_back = findViewById(R.id.btn_back);
        mEd_search_content = findViewById(R.id.ed_search_content);
        mBtn_search_go = findViewById(R.id.btn_search_go);
        mFramelayout = findViewById(R.id.framelayout_search_content);//搜索下方的布局


    }

    private void initView() {

    }

    private void initEvent() {
        mBtn_back.setOnClickListener(v -> finish());//返回按钮返回事件

        //点击搜索按钮事件
        mBtn_search_go.setOnClickListener(v -> {
            Editable text = mEd_search_content.getText();
            requstSearchData(text.toString());
        });

        //搜索框内容改变监听事件
        mEd_search_content.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                LogUtil.d(TAG, s.length() + ":::length>>>" + s.toString());
                mSearchPresenter.getRecommendWord(s.length() > 0 ? s.toString() : null);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    private void requstSearchData(String text) {
        //初始化加载器
        if (mLoaded == null) {
            mLoaded = new LoaderView(this) {
                @Override
                public View getSuccessView(ViewGroup container) {

                    return createSuccessView(container);
                }
            };
        }
        mFramelayout.removeAllViews();
        mFramelayout.addView(mLoaded);
        mLoaded.updateStatus(LoaderView.UIStatus.LOADING);//加载状态
        if (!text.trim().equals(""))
            mSearchPresenter.getSearchContent(text);//请求数据
    }

    /**
     * 创建一个成功获得页面
     *
     * @param container
     * @return
     */
    private View createSuccessView(ViewGroup container) {
        View view = LayoutInflater.from(this).inflate(R.layout.fragment_search, container, false);
        RecyclerView recycler = view.findViewById(R.id.search_result_recycler);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(RecyclerView.VERTICAL);
        recycler.setHasFixedSize(true);
        recycler.setLayoutManager(layoutManager);
        mSearchAdapter = new SearchAdapter();
        mSearchAdapter.setOnCallBack((album, position) -> {
            AlbumDetailPresenter.getInstance().setmTargetAlbum(album); //将Album实体存进AlbumDetail实现类中
            Intent intent = new Intent(this, DetailActivity.class);
            startActivityForResult(intent, Constants.REQUEST_CODE); //进行跳转至下一个详情Activity
        });
        recycler.setAdapter(mSearchAdapter);

        //设置上下拉框架事件
        TwinklingRefreshLayout refresh = view.findViewById(R.id.refreshLayout);
        refresh.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onRefresh(TwinklingRefreshLayout refreshLayout) {
                requstSearchData(mEd_search_content.getText().toString());
                refresh.finishRefreshing();
            }

            @Override
            public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
                mSearchPresenter.loadMore();
                mSearchPresenter.setOnfinishLoadMore(str -> {
                    if (str != null) {
                        Toast.makeText(getApplicationContext(), str, Toast.LENGTH_SHORT).show();
                    }
                    refresh.finishLoadmore();
                });
            }
        });

        return view;
    }

    //+=====================================================- 以下为UI回调方法实现

    /**
     * 搜索结果
     *
     * @param albumList
     */
    @Override
    public void onSearchResultLoaded(List<Album> albumList) {
        mLoaded.updateStatus(LoaderView.UIStatus.SUCCESS);//成功状态
        mSearchAdapter.setData(albumList);
    }

    /**
     * 加载热搜词
     *
     * @param hotWordList
     */
    @Override
    public void onHotwordLoaded(List<HotWord> hotWordList) {

        mHotwordFragment = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.fragment_hotword, null, false);


        {
            DisplayUtils displayUtils = DisplayUtils.getInstance(this);
            //宽高包裹参数
            LinearLayout.LayoutParams textParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            textParams.leftMargin = displayUtils.dipToPx(5.0f);
            textParams.rightMargin = displayUtils.dipToPx(5.0f);
            textParams.topMargin = displayUtils.dipToPx(5.0f);
            textParams.bottomMargin = displayUtils.dipToPx(5.0f);
            //列
            LinearLayout rowsLine = new LinearLayout(this);
            LinearLayout.LayoutParams rowsParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
            rowsLine.setLayoutParams(rowsParams);
            rowsLine.setOrientation(LinearLayout.VERTICAL);


            //行
            LinearLayout colsLine = null;
            LinearLayout.LayoutParams colsParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);


            int maxWidth = this.getResources().getDisplayMetrics().widthPixels - displayUtils.dipToPx(60f);//获取当前屏幕最大宽度
            int colsWidth = maxWidth;

            boolean isNewLine = true;
            for (int i = 0; i < hotWordList.size(); i++) {
                if (isNewLine) {
                    colsLine = new LinearLayout(this);
                    colsLine.setLayoutParams(colsParams);
                    colsLine.setGravity(Gravity.CENTER_HORIZONTAL);
                    colsWidth = maxWidth;
                    isNewLine = false;
                }
                TextView textview = (TextView) LayoutInflater.from(this).inflate(R.layout.item_hotword, null, false);//热词组件
                textview.setText(hotWordList.get(i).getSearchword());
                textview.setLayoutParams(textParams);

                textview.setOnClickListener(v -> {
                    mEd_search_content.setText(textview.getText().toString());
                    requstSearchData(textview.getText().toString());
                });//设置点击事件

                textview.measure(0, 0);//重要!!!!使用那个此方法后才能获得组件宽度
                if (i == hotWordList.size() - 1) {
                    if (textview.getMeasuredWidth() < colsWidth) {
                        LogUtil.d(TAG, "1111else:text-width:::" + textview.getMeasuredWidth() + ",colsLine-width:::" + colsWidth + ",,str:" + hotWordList.get(i).getSearchword());
                        colsWidth -= textview.getMeasuredWidth();
                        colsLine.addView(textview);
                        rowsLine.addView(colsLine);
                    } else {
                        rowsLine.addView(colsLine);
                        LogUtil.d(TAG, "2222else:text-width:::" + textview.getMeasuredWidth() + ",colsLine-width:::" + colsWidth + ",,str:" + hotWordList.get(i).getSearchword());
                        LogUtil.d(TAG, "最后一行");
                        colsLine = new LinearLayout(this);
                        colsLine.setLayoutParams(colsParams);
                        colsLine.setGravity(Gravity.CENTER_HORIZONTAL);
                        colsLine.addView(textview);
                        rowsLine.addView(colsLine);
                    }
                } else if (textview.getMeasuredWidth() < colsWidth) {
                    LogUtil.d(TAG, "3333else:text-width:::" + textview.getMeasuredWidth() + ",colsLine-width:::" + colsWidth + ",,str:" + hotWordList.get(i).getSearchword());
                    colsWidth -= textview.getMeasuredWidth();
                    colsLine.addView(textview);

                } else {
                    LogUtil.d(TAG, "4444else:text-width:::" + textview.getMeasuredWidth() + ",colsLine-width:::" + colsWidth + ",,str:" + hotWordList.get(i).getSearchword());

                    rowsLine.addView(colsLine);
                    isNewLine = true;
                    i--;
                    continue;
                }
            }

            mHotwordFragment.removeAllViews();
            mHotwordFragment.addView(rowsLine);
        }


        mFramelayout.removeAllViews();
        mFramelayout.addView(mHotwordFragment);

    }

    /**
     * 联想关键词
     *
     * @param queryResults
     */
    @Override
    public void onRecommendSuggestWords(List<QueryResult> queryResults) {
        if (queryResults != null) {
            if (queryResults.size() != 0) {
                List<Map<String, String>> mapList = new ArrayList<>();
                for (QueryResult result : queryResults) {
                    HashMap<String, String> map = new HashMap<>();
                    map.put("keyword", result.getKeyword());
                    mapList.add(map);
                }

                LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                ListView listView = new ListView(this);
                listView.setLayoutParams(layoutParams);
                SimpleAdapter simpleAdapter = new SimpleAdapter(this, mapList, R.layout.item_search_suggest_word, new String[]{"keyword"}, new int[]{R.id.suggest_word});
                listView.setAdapter(simpleAdapter);
                listView.setOnItemClickListener((parent, view, position, id) -> {
                    mEd_search_content.setText(mapList.get(position).get("keyword"));
                    requstSearchData(mapList.get(position).get("keyword"));
                });

                mFramelayout.removeAllViews();
                mFramelayout.addView(listView);
            }
        }

    }

    /**
     * 加载更多
     *
     * @param albumList
     * @param hasResult 如果没有更多内容，应为false，否则为true
     */
    @Override
    public void onLoadMoreRecommendResult(List<Album> albumList, boolean hasResult) {

    }

    @Override
    protected void onDestroy() {
        if (mSearchPresenter != null) {
            mSearchPresenter=null;
        }
        super.onDestroy();
    }
}